#ifndef EZQAUDIOPLAYER_H
#define EZQAUDIOPLAYER_H

#include <QObject>
#include <QAudioOutput>
#include <QBuffer>
#include "decode/libavDecodeDefine.h"
#include "ezqaudioplayerbuffer.h"
#include "thread/ezqthread.h"
#include <QEventLoop>
#include <QEvent>
#include "ezqaudioplayerdefine.h"
//#include "decode/libavdecode.h"
//#include "stream/streambase.h"

class LibavDecode;
class StreamBase;

class EZQAudioPlayer : public QIODevice
{
    Q_OBJECT
public:
    explicit EZQAudioPlayer(QObject *parent = 0);
    static EZQAudioPlayer *sharePlayer();
signals:
//    void sigstateChanged(EZVoiceState);
    void sigStausChanged(EZQAudioPlayStatus);

    void sigReadDataEnd();
private slots:
    void slotFillBuf();
public slots:
    void onStreamAvailableChange(qint64 offset,qint64 dataLen);
    void onDecodeStateChange(LibavStatus);
    void onDecodePcmAvailableChange();

    void onAOStateChange(QAudio::State);

    void fillBuf();
private:
    LibavDecode *_decode;
    QMutex _decodeMutex;

    StreamBase *_stream;

    QAudioOutput *_player;
    QMutex _playerMutex;

    void initPlayer(const QAudioFormat &format);
    void cleanPlayer();

    friend class QIODevice;
    virtual qint64 readData(char *data, qint64 maxlen);
    virtual qint64 writeData(const char *data, qint64 len);
    qint64 _readPcmOil;
    qint64 _writePcmOil;
    qint64 _pcmBufferSize;
    unsigned char *_pcmBuffer;
    QMutex _pcmBufferMutex;

    QThread *_thread;

//    EZVoiceState _state;
//    QMutex _stateMutex;
//    void setState(const EZVoiceState &state);
    bool _willPlay;
    QMutex _statusMutex;
    EZQAudioPlayStatus _status;
    void setStatus(const EZQAudioPlayStatus &status);

    float _volume;
    qint64 _duration;
    qint64 _currentTime;

private:
    void _play();
//    void _playOrPause();
    void _pause(bool changestatus=true);
    void _stop(bool changeStatus=true);
public:
    StreamBase *stream() const;
    void setStream(StreamBase *stream);

    void play();
    void playOrPause();
    void pause();
    void stop();

    qint64 duration(); //microseconds

    EZQAudioPlayStatus status() const;

    bool willPlay() const;
    void setWillPlay(bool willPlay);
    float volume() const;
    void setVolume(float volume);
    qint64 currentTime(); //microseconds
    void setCurrentTime(const qint64 &currentTime);//microseconds
};

#endif // EZQAUDIOPLAYER_H
